<template>
  <el-dialog
    class="add-edit-dialog"
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="1135px"
  >
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="规则名称" prop="ruleName">
            <el-input v-model="form.ruleName" show-word-limit maxlength="20" style="width: 240px;" 
                      :disabled="isdetail"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="规则状态">
            <el-radio-group v-model="form.ruleStatus" v-remove-ariaHidden :disabled="isdetail">
              <el-radio label="01">
                启用
              </el-radio>
              <el-radio label="02">
                禁用
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="风险事件" prop="events">
            <el-select
              v-model="form.events"
              multiple
              collapse-tags
              placeholder="请选择"
              @change="handleEventsChange"
              style="width: 240px;"
              :disabled="isdetail"
            >
              <el-option
                v-for="item in riskEvents"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="应用范围" prop="vehicleIds">
            <div class="flex">
              <el-select
                class="mr10"
                style="width: 240px;"
                v-model="form.vehicleIds"
                multiple
                collapse-tags
                placeholder="请选择车辆"
                :disabled="isdetail"
              >
                <el-option
                  v-for="item in carList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
              <span class="choice-text-btn" @click="choiceCar" v-if="!isdetail">选择车辆</span>
            </div>
          </el-form-item>   
        </el-col>
      </el-row>
    </el-form>

    <div class="flex">
      <div class="table-tit width128">
        告警项目
      </div>
      <div class="table-tit width380">
        处理条件
      </div>
      <div class="table-tit width130">
        告警等级
      </div>
      <div class="table-tit width150">
        处理方式
      </div>
      <div class="table-tit width300">
        通知内容
      </div>
    </div>
    <div class="flex flex-hc p10 none-event" v-if="!form.events.length">
      暂无数据，请先选择风险事件
    </div>
    <div class="dialog-main" :class="{ active: !form.events.length }">
      <div class="flex demo-box" v-for="bigItem in allRiskEventsData" :key="bigItem.value">
        <div class="demo-name items width128 flex flex-vc flex-j-start conditions-text">
          {{ bigItem.label }}
        </div>
        <div>
          <div class="conditions width380" v-for="demoItem in bigItem.riskEventsDetail" :key="demoItem.timeKey">
            <div v-for="(item) in demoItem.data" :key="item.conditionId" class="mb10">
              <div class="flex flex-vc font12">
                <el-checkbox 
                  v-model="item.checked" 
                  :true-label="1" 
                  :false-label="0" 
                  class="mr10" 
                  @change="handleCheck(item)"
                  :disabled="isdetail"
                />
                <div class="flex flex-vc font12 row-wrap">
                  <div v-for="(v,k) in item.conditionDescArr" :key="k">
                    <div v-if="!v.attrType" class="mr5 conditions-text">
                      {{ v.value }}
                    </div>
      
                    <el-input-number 
                      class="mr5 small-input" :controls="false" style="width: 60px;" 
                      size="mini" v-if="v.attrType == '01'" v-model="item.attrs[v.times-1].attrValue"
                      :disabled="isdetail"
                    />
                    <div v-if="v.attrType == '02'" class="mr5" />
                    <div class="mr5">
                      <el-select class="small-input" v-if="v.attrType == '03'" v-model="item.attrs[v.times-1].attrValue" :disabled="isdetail">
                        <el-option
                          v-for="selectItem in item.attrs[v.times-1].options"
                          :key="selectItem.optionId"
                          :label="selectItem.optionName"
                          :value="selectItem.optionId"
                        />
                      </el-select>
                    </div>
                  </div>
                </div>
              </div>
              <div v-if="item.children" class="ml25 mt10">
                <div v-for="i in item.children" :key="i.conditionId">
                  <div class="flex flex-vc mb10">
                    <el-checkbox v-model="i.checked" :true-label="1" :false-label="0" class="mr10" />
                    <div v-for="(v,k) in i.conditionDescArr" :key="k">
                      <div v-if="!v.attrType" class="mr5 conditions-text">
                        {{ v.value }}
                      </div>
                      <el-input-number 
                        class="small-input mr5"
                        :controls="false" style="width: 60px;" size="mini" 
                        v-if="v.attrType == '01'" v-model="i.attrs[v.times-1].attrValue"
                        :disabled="isdetail"
                      />

                      <div v-if="v.attrType == '02'" class="mr5" />
                      <div class="mr5">
                        <el-select 
                          v-if="v.attrType == '03'" 
                          v-model="i.attrs[v.times-1].attrValue" 
                          class="small-input"
                          style="width: 100px;"
                          :disabled="isdetail"
                        >
                          <el-option
                            v-for="c_item in i.attrs[v.times-1].options"
                            :key="c_item.optionValue"
                            :label="c_item.optionName"
                            :value="c_item.optionValue"
                          />
                        </el-select>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="conditions-btns" v-if="!isdetail">
              <el-button 
                plain
                class="btn-common" 
                @click="handelConditionsDel(demoItem,bigItem)" 
                :disabled="bigItem.riskEventsDetail.length <= 1"
              >
                <i class="el-icon-minus" />
              </el-button>
              <el-button type="primary" class="btn-common" @click="handelConditionsAdd(demoItem,bigItem)">
                <i class="el-icon-plus" />
              </el-button>
            </div>
          </div>
        </div>
         
        <div class="flex flex-d-column">
          <div class="level width130 flex1" v-for="levelItem in bigItem.riskEventsDetail" :key="levelItem.timeKey">
            <div>
              <el-select style="width: 100px;" v-model="levelItem.riskLevel" class="meduim-input" :disabled="isdetail">
                <el-option
                  v-for="levleItem in levelOptions"
                  :key="levleItem.value"
                  :label="levleItem.label"
                  :value="levleItem.value"
                />
              </el-select>
            </div>
          </div>
        </div>

        <div class="ways-box width150">
          <div class="ways width150" v-for="waysItem in bigItem.riskEventsDetail" :key="waysItem.timeKey">
            <div class="ways-item flex flex-vc flex-hc" v-for="waysItemChild in waysItem.alarmHandleConfigs" :key="waysItemChild.timeKey">
              <el-select style="width: 100px;" v-model="waysItemChild.handleType" class="meduim-input" :disabled="isdetail">
                <el-option
                  v-for="waysSelectTtem in waysOptions"
                  :key="waysSelectTtem.value"
                  :label="waysSelectTtem.label"
                  :value="waysSelectTtem.value"
                  :disabled="waysItem.alarmHandleConfigs.map(v => v.handleType).includes(waysSelectTtem.value)"
                />
              </el-select>

              <div class="ways-btns" v-if="!isdetail">
                <el-button plain class="btn-common" @click="handleWaysDel(waysItemChild,waysItem.alarmHandleConfigs)" :disabled="waysItem.alarmHandleConfigs.length <=1">
                  <i class="el-icon-minus" />
                </el-button>
                <el-button type="primary" class="btn-common" @click="handleWaysAdd(waysItemChild,waysItem.alarmHandleConfigs)" :disabled="waysItem.alarmHandleConfigs.length >=2">
                  <i class="el-icon-plus" />
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <div class="content-box width300">
          <div class="contents width300" v-for="contentItem in bigItem.riskEventsDetail" :key="contentItem.timeKey">
            <div class="contents-item flex flex-d-column flex-hc flex-vc" v-for="contentItemChild in contentItem.alarmHandleConfigs" :key="contentItemChild.timeKey">
              <div v-if="contentItemChild.handleType == '01'">
                <div class="flex flex-vc mb5">
                  <div class="fw600 w90 tar">
                    通知内容：
                  </div>
                  <div>
                    <el-select class="meduim-input" style="width: 180px;" v-model="contentItemChild.notifyContentType" @change="handleContentChange(contentItemChild,bigItem)">
                      <el-option
                        v-for="contentSelectItem in contentOptions"
                        :key="contentSelectItem.value"
                        :label="contentSelectItem.label"
                        :value="contentSelectItem.value"
                      />
                    </el-select>
                  </div>
                </div>
                <div class="flex flex-j-end" v-if="contentItemChild.notifyContentType === '01'">
                  <el-input 
                    class="meduim-input active"
                    type="text"
                    placeholder="请输入自定义内容" style="width: 180px;" 
                    v-model="contentItemChild.notifyContent" 
                    :disabled="contentItemChild.notifyContentType === '01'"
                  />
                </div>
                <div v-if="contentItemChild.notifyContentType === '02'" class="flex">
                  <div class="fw600 w90 tar">
                    自定义内容：
                  </div>
                  <el-input 
                    class="custom meduim-input"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入自定义内容" style="width: 180px;" 
                    v-model="contentItemChild.notifyContent" 
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <span slot="footer" class="dialog-footer">
      <div class="flex flex-j-end">
        <el-button type="primary" @click="handleSave" size="medium" style="width: 72px;" 
                   v-if="!isdetail">保 存</el-button>
      </div>
    </span>

    <ChoiceCarDialog 
      :visible.sync="innerVisible" 
      @onSaveCarList="handleSaveCarList" 
      :select-keys="form.vehicleIds" 
      :config-id="form.configId" 
      :car-list-data="carList"
    />
  </el-dialog>
</template>

<script>
  import ChoiceCarDialog from './ChoiceCarDialog.vue'
  import { cloneDeep } from 'lodash-es'
  //ruleData为模拟后端提供的条件模板数据
  import { ruleData } from './rule'

  export default {
    components: {
      ChoiceCarDialog
    },
    watch: {
      dialogVisible(val) {
        if (!val) {
          this.form = this.$options.data().form;
          this.$refs.form.resetFields();
          this.returnViewSelect(this.form.events);
          this.alarmConditions  = [];
          this.carList = [];
          this.isdetail = false
        }
      }
    },
    data() {
      return {
        isdetail: false,
        carList: [],
        levelOptions: [
          {value: 3, label: '低风险'},
          {value: 2, label: '中风险'},
          {value: 1, label: '高风险'},
        ],
        contentOptions: [
          {
            value: '01',
            label: '默认内容'
          },
          {
            value: '02',
            label: '自定义内容'
          }
        ],
        waysOptions: [
          {
            value: '01',
            label: '语音通知'
          },
          {
            value: '02',
            label: '人工处理'
          }
        ],
        allRiskEventsData: [],
        conditionModel: {},//处理后的模板
        alarmConditions: [],//单个告警项目项数据集合
        riskEvents: [{
          value: '01',
          label: '分神驾驶'
        }, {
          value: '02',
          label: '抽烟'
        }, {
          value: '03',
          label: '疲劳驾驶'
        }],
        rules: {
          ruleName: [
            { required: true, message: '请输入规则名称', trigger: 'blur' },
          ],
          vehicleIds: [
            { required: true, message: '请选择车辆', trigger: 'blur' },
          ],
          events: [
            { required: true, message: '请选择风险事件', trigger: 'blur' },
          ],
        },
        form: {
          vehicleIds: [],
          vehicleConfig: {
            vehicleIds: [],
          },
          events: [],
          ruleStatus: '01',
          ruleName: '',
        },
        title:'告警通知规则配置',
        innerVisible: false,
        dialogVisible: false
      };
    },
    methods: {
      handleSaveCarList(carsData) {
        console.log('carsData',carsData)
        this.carList = carsData
        this.form.vehicleIds = carsData.map(item => item.id)
      },
      handleEventsChange(events) {
        console.log('eventChange',events)
        this.returnViewSelect(events)
      },
      handleWaysAdd(waysItem,ways) {
        const timekey = waysItem.timeKey;
        const waysItemIndex = ways.findIndex(item => item.timeKey == timekey);
        ways.splice(waysItemIndex + 1, 
                    0,
                    { 
                      handleType: '',
                      notifyContent: '',
                      notifyContentType: '',
                      timeKey: Date.now(),
                    });
      },
      handleWaysDel(waysItem,ways) {
        const waysKey = waysItem.timeKey;
        const waysItemIndex = ways.findIndex(item => item.timeKey == waysKey);

        ways.splice(waysItemIndex, 1)
      },
      handelConditionsAdd(demoItem,bigItem) {
        const timekey = demoItem.timeKey;
        const demoItemIndex = bigItem.riskEventsDetail.findIndex(item => item.timeKey === timekey);

        bigItem.riskEventsDetail.splice(
          demoItemIndex + 1, 
          0,
          { ...cloneDeep(this.conditionModel),
            timeKey: Date.now(),
            riskLevel: 1,
            alarmHandleConfigs: [
              { 
                handleType: '02',
                handleConfigId: '01',
                notifyContent: '',
                contentType: '',
                timeKey: Date.now(),
              }
            ],
          })
      },
      handelConditionsDel(demoItem,bigItem) {
        const timekey = demoItem.timeKey;
        const demoItemIndex = bigItem.riskEventsDetail.findIndex(item => item.timeKey === timekey);

        bigItem.riskEventsDetail.splice(demoItemIndex, 1)
      },
      getModelData() {
        const modelData = ruleData
        this.handleModel(modelData)
        this.conditionModel = { data: modelData }
        this.alarmConditions.push(
          { ...cloneDeep(this.conditionModel),
            timeKey: Date.now(),
            riskLevel: 1,
            alarmHandleConfigs: [
              { 
                handleType: '02',
                handleConfigId: '01',
                notifyContent: '',
                contentType: '',
                timeKey: Date.now(),
              }
            ],
          });
        console.log('this.alarmConditions', this.alarmConditions)
      },
      handleModel(data) {
        data.forEach(item=> {
          let conditionDescArr = [];

          if (conditionDescArr) {
            const descStrArr = item.conditionDesc.replaceAll('{}','*{}*').split('*').filter(i => i !== '');
            conditionDescArr = this.validateRuleModel(descStrArr)
          }

          if (item.attrs && item.attrs.length) {
            conditionDescArr.forEach(v => {
              if (v.value=='{}'){
                v.attrType = item.attrs[v.times - 1].attrType;
                v.attrId = item.attrs[v.times - 1].attrId;

                const isHave = item.attrs[v.times - 1].hasOwnProperty('attrValue');
                !isHave && (this.$set(item.attrs[v.times - 1], 'attrValue', ''));
              }
            })
          }        

          item.conditionDescArr = conditionDescArr;

          if (item.children) {
            this.handleModel(item.children)
          }
        })
      },
      validateRuleModel(data) {
        const result = [];
        const timesArr = {};

        data.forEach((item, index) => {
          if (result.findIndex((v) => v.value == item) == -1) {
            result.push({
              value: item,
              index: index,
              times: 1,
            });
            timesArr[item] = 1;
          } else {
            timesArr[item]++;
            result.push({
              value: item,
              index: index,
              times: timesArr[item],
            });
          }
        });

        return result;
      },
      choiceCar() {
        this.innerVisible = true
      },
      //将处理条件树形数据平铺展开
      handleChild(data) {
        const allData = []
        if (!data || !data.length) return []

        data.forEach(item => {
          if (item.children && item.children.length > 0) {
            allData.push(item,...item.children)
          } else {
            allData.push(item)
          }
        })

        return allData
      },
      handleSave() {
        console.log('allRiskEventsData',this.allRiskEventsData)
        this.$refs['form'].validate(async(valid) => {
          if (!valid) return;

          let params = {
            configId: this.form.configId,
            ruleName: this.form.ruleName,
            ruleStatus: this.form.ruleStatus,
            vehicleConfig: {
              vehicleIds: this.form.vehicleIds
            },
            alarmConfigBases: this.allRiskEventsData.map(item => {
              return {
                alarmType: item.value,
                alarmTypeName: item.label,
                alarmConfigList: item.riskEventsDetail.map(v => {
                  return {
                    alarmConfigId: item.alarmConfigId,
                    alarmType: item.value,
                    riskLevel: v.riskLevel,
                    alarmHandleConfigs: v.alarmHandleConfigs.map(w => {
                      return {
                        handleType: w.handleType,
                        notifyContent: w.notifyContent,
                        notifyContentType: w.notifyContentType,
                      }
                    }),
                    alarmConditionConfigRelations: this.handleChild(v.data).map(w=>{
                      return {
                        aggregation: w.aggregation,
                        attrValues: w.attrs.map((x => {
                          return {
                            attrId: x.attrId,
                            attrKey: x.attrKey,
                            attrValue: x.attrValue
                          }
                        })),
                        checked: w.checked,
                        conditionId: w.conditionId
                      }
                    })
                  }
                }),
              }
            })
          }

          console.log('提交给后端的数据对象params', params)

          this.dialogVisible = false
          this.$emit('refresh',this.form)
        });
      },
      returnViewSelect(eventsId) {
        let eventsData = [];

        this.form.events = eventsId
        this.riskEvents.forEach((item) => {
          if (eventsId.indexOf(item.value) != -1) {
            eventsData.push({
              value: item.code,
              label: item.label,
            })
          }
        });

        this.allRiskEventsData = [];
        eventsData.forEach(item  => {
          this.allRiskEventsData.push({
            ...item,
            riskEventsDetail: [cloneDeep(...this.alarmConditions)],
            riskLevel: '02',
          })
        })

        console.log('this.allRiskEventsData',this.allRiskEventsData)
      },
      //回显处理条件数据
      handleRelationsData(v,item) {
        if (v.conditionId == item.conditionId) {
          item.attrs.forEach((w) => {
            v.attrValues.forEach((x) => {
              if (w.attrId == x.attrId) {
                w.attrValue = x.attrValue
              }
            })
          });
          item.checked = 1;
        }
      },
      //处理条件数据
      handleRelations(relations) {
        console.log('relations',relations)
        if (relations.length == 0) return
        const newRelations = cloneDeep(this.conditionModel.data).map(item => {
          relations.forEach(v => {
            this.handleRelationsData(v,item)
          })

          if (item.children && item.children.length > 0) {
            item.children.map((v) => {
              relations.forEach((w) => {
                this.handleRelationsData(w,v)
              })
            })
          }
          return item
        });
        console.log('newRelations',newRelations)

        return newRelations
      },
      showDialog(row,sign) {
        this.getModelData()
        if (row) {
          this.isdetail = sign === 'detail'
          this.returnViewSelect(['01','02','03'])

          // // 调用后端接口回显动态表格数据
          // getRiskRuleDetail({ configId: row.configId }).then((res) => {
          //   if (res.success) {
          //     const { data } = res;
          //     this.form.configId = data.configId;
          //     this.form.events = data.alarmTypes;
          //     this.form.ruleName = data.ruleName;
          //     this.form.vehicleIds = data.vehicleConfig.vehicleIds;
          //     this.form.ruleStatus = data.ruleStatus;
          //     this.carList = (data.vehicleConfig.vehicles || []).map(item => {
          //       return {
          //         id: item.vehicleId,
          //         label: item.plateNo,
          //       }
          //     });
          //     data.alarmConfigBases.forEach(item => {
          //       this.allRiskEventsData.push({
          //         label: item.alarmTypeName,
          //         riskEventsDetail: item.alarmConfigList.map((v,vIndex) => {
          //           return {
          //             alarmHandleConfigs: v.alarmHandleConfigs.map((w,wIndex) => {
          //               return {
          //                 ...w,
          //                 timeKey: String(Date.now()) + String(wIndex + 1)
          //               }
          //             }),
          //             data: this.handleRelations(v.alarmConditionConfigRelations),
          //             riskLevel: v.riskLevel,
          //             timeKey: String(Date.now()) + String(vIndex + 1)
          //           }
          //         }),
          //         value: item.alarmType,
          //       });
          //     });
          //   }
          // });
        } 
        this.dialogVisible = true
      }
    },
  };
</script>

<style lang="scss" scoped>
  @mixin widthGenerator($value) {
    .width#{$value} {
      width: $value * 1px;
    }
  }

  @include widthGenerator(90);
  @include widthGenerator(128);
  @include widthGenerator(380);
  @include widthGenerator(130);
  @include widthGenerator(150);
  @include widthGenerator(300);

  @import './AddEditDialog.scss'
</style>
